class Proposal < ActiveRecord::Base
  validates_presence_of :requestor, :empoweringJurisdiction, :empoweredJurisdiction  
  
  belongs_to :empoweringJurisdiction, :class_name => "Jurisdiction"
  belongs_to :empoweredJurisdiction, :class_name => "Jurisdiction"
  belongs_to :requestor, :class_name => "User"
  has_many :approvals
  
  def self.find_proposals_by_responsibility user
    joins("
    inner join jurisdiction_members on 
    jurisdiction_members.jurisdiction_id = proposals.empoweringJurisdiction_id or
    jurisdiction_members.jurisdiction_id = proposals.empoweredJurisdiction_id
    where jurisdiction_members.user_id = #{user.id}      
    and workflow_state = 'awaiting_approval'  
    group by id
    ")
  end
  
  def approval_for role, jurisdiction
    approvals.select{|a| a.jurisdiction == jurisdiction && 
                         a.role == role}.first
  end
  
  def nice_workflow_state
    case workflow_state
      when "awaiting_approval" then "Awaiting approval"
      when "awaiting_final_approval" then "Awaiting final approval"
      when "approved" then "Approved"
    end
  end
  
  include Workflow
  workflow do
    state :awaiting_approval do
      event :approve, :transitions_to => :awaiting_final_approval
      event :reject, :transitions_to => :rejected
    end
    state :awaiting_final_approval do
      event :approve, :transitions_to => :approved
      event :reject, :transitions_to => :rejected
    end
    state :approved
    state :rejected
  end
end
